from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.traits.MyModelTrait import MyModelTrait
from app.models.AdminMenu import AdminMenu
from app.models.AdminActionLog import AdminActionLog
from masonite.facades import Session
from app.my_package.MyPackage import MyValidator


class AdminMenuController(Controller):
    uri = "/admin/menu"
    temp = "admin.menu"

    def index(self, request: Request, view: View):
        uri  = self.uri + '/index'
        data = {
            'uri': self.uri,
            'title': MyControllerTrait.get_permission_title(uri),
            'menus': MyControllerTrait.get_menu_nav(uri)
        }

        return view.render(self.temp + ".index", data)

    def create(self, request: Request, view: View):

        data = {
            'uri': self.uri,
            'pids': AdminMenu.get_all_pid(),
        }
        return view.render(self.temp + ".create", data)

    def show(self, request: Request, response: Response):
        title = request.input("title")
        is_show = request.input("is_show")
        page = request.input("page", 1)
        limit = request.input('limit', 10)

        table = AdminMenu.get_table_name()
        order = 'id DESC'
        where = ''

        if len(title) > 0:
            where += " AND title LIKE '%{0}%'".format(title)
        if is_show.isdigit():
            where += " AND is_show = {0}".format(is_show)

        titles = AdminMenu.get_title()
        total, admin_menus = MyModelTrait.search_for_show(table, where, '*', int(page), int(limit), order)
        if admin_menus is not None:
            for index, admin_menu in enumerate(admin_menus):
                admin_menus[index]['is_show'] = AdminMenu.FIELDS['is_show'][admin_menu['is_show']]
                admin_menus[index]['pid'] = titles[admin_menu['pid']]
                admin_menus[index]['created_at'] = MyControllerTrait.time_format_conversion(admin_menu['created_at'])
                admin_menus[index]['updated_at'] = MyControllerTrait.time_format_conversion(admin_menu['updated_at'])

        data = {
            'code': 0,
            'message': 'success',
            'total': total,
            'data': admin_menus
        }
        return response.json(data)

    def edit(self, request: Request, response: Response,view: View):
        admin_menu_id = request.input('id')

        b, m = MyValidator.gt(admin_menu_id, 0)
        if b is False:
            return response.redirect(location=self.uri+'/index', status=302)

        admin_menu = AdminMenu.where('id', admin_menu_id).first()
        if admin_menu is None:
            return response.redirect(location=self.uri + '/index', status=302)

        data = {
            'uri': self.uri,
            'pids': AdminMenu.get_all_pid(),
            'data': admin_menu,
        }
        return view.render(self.temp + ".edit", data)

    def store(self, request: Request, response: Response):
        pid = request.input('pid')
        rank = request.input("rank")
        title = request.input('title')
        uri = request.input('uri')
        is_show = request.input('is_show')

        b, m = MyValidator.is_integer(int(pid))
        if b is False:
            return response.json({'code': 0, 'message': '上级菜单' + m})
        b, m = MyValidator.is_integer(int(rank))
        if b is False:
            return response.json({'code': 0, 'message': '排序' + m})
        if is_show in [0, 1]:
            return response.json({'code': 0, 'message': '显示仅支持 0、1'})
        b, m = MyValidator.ch_alpha_num(title)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.between(title, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.uri(uri)
        if b is False and uri != "#":
            return response.json({'code': 0, 'message': '链接' + m})
        b, m = MyValidator.between(uri, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '链接' + m})

        admin_menu = AdminMenu.where('uri', uri).first()
        if admin_menu is not None and uri != "#":
            return response.json({'code': 0, 'message': '{0} 已存在'.format(uri)})

        AdminMenu.generate_log(pid, rank, title, uri, is_show)
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}({1})".format(title, uri)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})

    def update(self, request: Request, response: Response):
        id = request.input("id")
        pid = request.input('pid')
        rank = request.input('rank')
        title = request.input('title')
        uri = request.input('uri')
        is_show = request.input('is_show')

        b, m = MyValidator.is_integer(int(id))
        if b is False:
            return response.json({'code': 0, 'message': 'id' + m})
        b, m = MyValidator.is_integer(int(pid))
        if b is False:
            return response.json({'code': 0, 'message': '上级菜单' + m})
        b, m = MyValidator.is_integer(int(rank))
        if b is False:
            return response.json({'code': 0, 'message': '排序' + m})
        if is_show in [0, 1]:
            return response.json({'code': 0, 'message': '显示仅支持 0、1'})
        b, m = MyValidator.ch_alpha_num(title)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.between(title, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.uri(uri)
        if b is False and uri != "#":
            return response.json({'code': 0, 'message': '链接' + m})
        b, m = MyValidator.between(uri, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '链接' + m})

        admin_menu = AdminMenu.where('id', id).first()
        if admin_menu is None:
            return response.json({'code': 0, 'message': '未知数据'})

        admin_menu.update({
            'pid': pid,
            'rank': rank,
            'title': title,
            'uri': uri,
            'is_show': is_show
        })
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}({1})".format(title, uri)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': "成功"})

    def destroy(self, request: Request, response: Response):
        id = request.input('id')
        b, m = MyValidator.is_integer(int(id))
        if b is False:
            return response.redirect(location=self.uri+'/index', status=302)

        admin_menu = AdminMenu.where('id', id).first()
        if admin_menu is None:
            return response.redirect(location=self.uri+'/index', status=302)

        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}({1})".format(admin_menu.title, admin_menu.uri)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        # 删除子菜单
        AdminMenu.where('pid', admin_menu.id).delete()
        admin_menu.delete()
        return response.json({'code': 1, 'message': '成功'})

